package com.nacos.temp2.controller;

import com.nacos.temp2.controller.base.BaseRestController;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/nacos")
public class DemoRestController extends BaseRestController {

    /**
     * 服务列表
     * http://127.0.0.1:8080/nacos/services
     */
    @GetMapping("/services")
    public List<String> serviceId() {
        // 获取 服务ID列表
        return discoveryClient.getServices();
    }

    /**
     * 服务的地址列表
     * http://127.0.0.1:8080/nacos/details
     */
    @GetMapping("/details")
    public Map<String, List<URI>> address() {
        Map<String, List<URI>> serviceDetails = new HashMap<>();
        List<String> serviceIdList = discoveryClient.getServices();
        for (String serviceId : serviceIdList) {
            // 获取服务的实例列表
            List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances(serviceId);
            // 获取每个服务实例的网络地址
            List<URI> serviceURIs = serviceInstanceList.stream()
                    .map(ServiceInstance::getUri)
                    .collect(Collectors.toList());
            // 统计
            serviceDetails.put(serviceId, serviceURIs);
        }
        return serviceDetails;
    }

    /**
     * 远程调用示例 - 使用本地负载均衡器Ribbon
     * 【通过注解 @LoadBalanced 使用loadBalancerClient对象】
     * http://127.0.0.1:8080/nacos/invoke/diff?service=potyun-member-service&apiUrl=api/member/get/CACTU
     */
    @GetMapping("/invoke/diff")
    public Object invokeTest2(@RequestParam("service") String serviceId, @RequestParam("apiUrl") String apiUrl) {
        String requestUrl = "http://" + serviceId + "/" + apiUrl;
        return restTemplate.getForObject(requestUrl, String.class);
    }

    /**
     * 演示 - 使用本地负载均衡器Ribbon
     * 【直接使用loadBalancerClient对象】
     * http://127.0.0.1:8080/nacos/invoke/ribbon?service=potyun-member-service
     */
    @GetMapping("/invoke/ribbon")
    public ServiceInstance invokeTest3(@RequestParam("service") String serviceId) {
        return loadBalancerClient.choose(serviceId);//通过负载均衡算法获取被选择的服务实例，可用于执行远程调用
    }

}
